package com.dddframework.security.domain.phone.component;

import com.dddframework.security.domain.auth.model.AuthUserChecker;
import com.dddframework.security.domain.phone.model.PhoneAuthToken;
import com.dddframework.security.domain.auth.service.IUserDetailService;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

/**
 * 手机验证码登录
 *
 * @author zhouzx
 */
@Slf4j
@Getter
@Setter
public class PhoneAuthenticationProvider implements AuthenticationProvider {
    private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    private UserDetailsChecker detailsChecker = new AuthUserChecker();
    private IUserDetailService userService;

    @Override
    @SneakyThrows
    public Authentication authenticate(Authentication authentication) {
        PhoneAuthToken phoneAuthenticationToken = (PhoneAuthToken) authentication;
        String principal = phoneAuthenticationToken.getPrincipal().toString();
        String code = phoneAuthenticationToken.getCode();
        UserDetails userDetails = userService.loadUserByPhone(principal, code, true);
        if (userDetails == null) {
            log.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
        }
        // 检查账号状态
        detailsChecker.check(userDetails);

        PhoneAuthToken authenticationToken = new PhoneAuthToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(phoneAuthenticationToken.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PhoneAuthToken.class.isAssignableFrom(authentication);
    }
}